// 1. 安装了路由 yarn add vue-router 
// 2. 创建路由实例配置路由规则
import Confirm from '@/components/confirm'
import useStore from '@/store'
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return {
      top: 0, // 回到顶部
      behavior: 'smooth' // 平滑滚动 过渡效果
    }
    /*  if (savedPosition) {
       return savedPosition // 回退页面 保留上一次浏览的位置
     } else {
       return { top: 0 } // 让滚动条从0开始
     } */
  },
  history: createWebHashHistory(), // hash模式 #
  routes: [
    { path: '/login', component: () => import('@/views/login/index.vue') },
    { path: '/login/callback', component: () => import('@/views/login/callback.vue') },
    { path: '/playground', component: () => import('@/views/playground/index.vue') },
    {
      path: '/', component: () => import('@/views/layout/index.vue'), children: [
        { path: '', component: () => import('@/views/home/index.vue') },
        { path: '/category/:id', component: () => import('@/views/category/index.vue') },
        { path: '/category/sub/:id', component: () => import('@/views/category/sub.vue') },
        { path: '/goods/:id', component: () => import('@/views/goods/index.vue') },
        { path: '/cart', component: () => import('@/views/cart/index.vue') },
        { path: '/member/checkout', component: () => import('@/views/member/pay/checkout.vue') },
        { path: '/member/pay', component: () => import('@/views/member/pay/index.vue') },
        { path: '/pay/callback', component: () => import('@/views/member/pay/callback.vue') },
        {
          path: '/member', component: () => import('@/views/member/layout/index.vue'), children: [
            { path: '', component: () => import('@/views/member/home/index.vue') },
            { path: 'order', component: () => import('@/views/member/order/index.vue') },
          ]
        }
      ]
    },
  ]
})
// 添加路由前置导航守卫
router.beforeEach((to, from, next) => {
  // 如果是已经登录的用户, 想去哪就去哪
  const { user } = useStore()
  if (user.userInfo.token) {
    next()
  } else {
    // 如果没有登录, 判断去的页面是不是 以/member开头的 强制登录 反之 放行
    if (to.path.includes('/member')) {
      Confirm({ title: '温馨提示', text: '亲,下单之前请先登录' }).then(() => {
        // to 记录了之前要去的页面的信息，但是被拦截下拉不让过去，强制去到了登录页
        // next() 和 router.push() 中写的参数是一样的
        // router.push('/路径?a=10')
        // router.push({ path: '/路径', query: { a: 10 } })
        // next(`/login?redirectURL=${to.fullPath}`)
        next({
          path: '/login',
          query: {
            redirectURL: to.fullPath
          }
        })
      }).catch(() => { })
    } else {
      next()
    }
  }
})


// 3. 导出
export default router
// 4. 在main.ts中挂载
// 5. app.vue文件中准备路由出口